﻿(function($) {
	$.fn.frogMenu = function() {
		var config = {    
			sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
			interval: 100, // number = milliseconds for onMouseOver polling interval    
			over: HoverOver, // function = onMouseOver callback (REQUIRED)    
			timeout: 500, // number = milliseconds delay before onMouseOut    
			out: HoverOut // function = onMouseOut callback (REQUIRED)    
		};
		
		function buildMenu(menu) {
			menu.children('li').each(function() {
				$(this).addClass('fm-top').data('fm-state', {'subMenuSource': null});
					
				$(this).children('ul').each(function() {
					$(this).addClass('fm-sub').children('li').each(buildSubMenu);
				});
			});
			
			$('.fm-top > a, .fm-sub-header > a').live('click', function() {
				return false;
			});
			menu.find("li.fm-sub").css({'opacity':'0'});
		};

		function buildSubMenu() {
			if ($(this).children('ul').length > 0) {
				$(this).addClass('fm-sub-header');
				
				$(this).children('ul').each(function() {
					$(this).children('li').each(function() {
						childrenUL = $(this).children('ul');
						if (childrenUL.length > 0) {
							$(this).addClass('fm-middle').click(menuItemClick);
							childrenUL.css({'display': 'none'});
						}
						else {
							$(this).addClass('fm-end');
						};
					});
				});
			}
			else {
				$(this).addClass('fm-end fm-single');
			};
		};
		
		function createSubMenu(topItem, subMenuSource) {
			// Remove All previously created Sub Menus
			$('.fm-sub-wrapper').remove(); 
			
			topItem.children('a').css({'color' : '#0079A6', 'padding-top': '8px'});

			subMenu = subMenuSource.clone().addClass('fm-sub');
			subMenu.children('li').each(buildSubMenu);
			subMenu.appendTo(topItem);
			
			topItem.data('fm-state').subMenuSource = subMenuSource;

			subMenu.css({'display': 'block'});
			subMenuWidth = calcSubMenuWidth(subMenu);
			subMenu.css({'width' : subMenuWidth});

			subMenu.wrap('<div class="fm-sub-wrapper"></div>').
				before('<div class="fm-sl"></div><div class="fm-sr"></div>').
				after('<div class="fm-sbl"></div><div class="fm-sbr"></div><div class="fm-sbm"></div>');
			
			subFooterHeight = 0;
			if (!subMenuSource.parent().hasClass('fm-top')) {
				subFooter = $('<div class="fm-sub-footer"></div>').insertAfter(subMenu);
				
				bcChildText = subMenuSource.parent().children('a').text();
				bcParentText = subMenuSource.parent().parent().parent().children('a').text();
				subFooter.append('<div class="fm-breadcrumbs"><span class="fm-bc-parent">' + bcParentText + '</span> | <span class="fm-bc-child">' + bcChildText + '</span></div>');
			
				subFooterHeight = subFooter.outerHeight();
				$('<div class="fm-sl"></div>').insertBefore(subFooter).css({'height': subFooterHeight + 'px'});
				$('<div class="fm-sr"></div>').insertBefore(subFooter).css({'height': subFooterHeight + 'px'});
				subFooter.append('<div class="fm-button">Назад</div>').click(backClick);
			};
			
			subMenu.masonry({ columnWidth: 176, itemSelector: '.fm-sub-header, .fm-single' });

			wrapper = subMenu.parents('.fm-sub-wrapper');
			subMenuHeight = subMenu.outerHeight();
			wrapper.css({'height': subMenuHeight + subFooterHeight + 5 + 'px', 'width': subMenu.outerWidth() + 20 + 'px'});
			subMenuHeight = {'height': subMenuHeight + 'px'};
			wrapper.children('.fm-sl').eq(0).css(subMenuHeight);
			wrapper.children('.fm-sr').eq(0).css(subMenuHeight);
			wrapper.stop().fadeTo('fast', 1).show();
			t = topItem.outerHeight() + 5;
			wrapper.css({'left' : '0px', 'top' : t + 'px'});
			
			return wrapper;
		};
		
		function menuItemClick() {
			var $this = $(this),
				topItem = $this.parents('.fm-top'),
				middleItemIndex = $this.index(),
				subHeaderIndex = $this.parent().parent().index(),
				newSubMenuSource = topItem.data('fm-state').subMenuSource.children('li').eq(subHeaderIndex).
					children('ul').children('li').eq(middleItemIndex).children('ul');
			
			createSubMenu(topItem, newSubMenuSource);
			return false;
		};
		
		function backClick() {
			topItem = $(this).parents('.fm-top');
			newSubMenuSource = topItem.data('fm-state').subMenuSource.parent().parent().parent().parent();
			
			if (newSubMenuSource.parent().hasClass('fm-sub-header')) {
				alert('has'); // todo
			}
			else {
				createSubMenu(topItem, newSubMenuSource);
			};
		};
		
		function calcSubMenuWidth(subMenu) {
			var subMenuWidth = 0, headers = subMenu.children("li.fm-sub-header"),
				rows = Math.floor((headers.length - 1) / 4) + 1,
				cols = Math.floor(headers.length / rows);
				
			if (cols * rows > headers.length) {
				cols += 1;
			};
			
			//Calculate row
			i = 1;
			headers.each(function() {					
				subMenuWidth += $(this).outerWidth(true) + 8; 
				
				if (i >= cols) {
					return false;
				};
				
				i += 1;
			});	
			
			if (subMenuWidth == 0) {
				subMenuWidth = 300;
			};
			
			return subMenuWidth;
		};

		function hideSubMenu(topItem, wrapper) {
			topItem.children('a').css({'color' : '#00A0E3'});
			wrapper.stop().fadeTo('fast', 0, function() {
				$(this).hide(); 
			});
		}
		
		function HoverOver() {
			$this = $(this);
			
			if ($this.hasClass('fm-top') && $this.data('fm-state').subMenuSource != null) {
				createSubMenu($this, $this.data('fm-state').subMenuSource);
			}
			else {
				createSubMenu($this, $(this).find(".fm-sub"));
			};
		};
	
		function HoverOut(){ 
			hideSubMenu($(this), $(this).find(".fm-sub-wrapper"));
		};
	 
		return this.each(function() {
			var $this = $(this);
			buildMenu($this);
			$this.children("li").hoverIntent(config);
		});
	};
})(jQuery);